/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.asl.member;

import com.hboxs.asl.Message;
import com.hboxs.asl.Setting;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.BaseEntity.Save;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.SafeKey;
import com.hboxs.asl.service.CaptchaService;
import com.hboxs.asl.service.MailService;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.util.SettingUtils;
import com.hboxs.asl.util.SpringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * Controller - 密码
 */
@Controller("aslPasswordController")
@RequestMapping("/pw")
public class PasswordController extends BaseController {
    protected Logger logger = Logger.getLogger(getClass());

    @Resource(name = "captchaServiceImpl")
    private CaptchaService captchaService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "mailServiceImpl")
    private MailService mailService;

    /**
     * 找回密码
     */
    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public String find(Model model) {
        model.addAttribute("captchaId", UUID.randomUUID().toString());
        return "/asl/password/find";
    }

    /**
     * 找回密码提交
     */
    @RequestMapping(value = "/find", method = RequestMethod.POST)
    public
    @ResponseBody
    Message find(String captchaId, String captcha, String email) {
//		System.out.println("## Forget Password Started...");
        if (!captchaService.isValid(Setting.CaptchaType.findPassword, captchaId, captcha)) {
            logger.error(SpringUtils.getMessage("asl.captcha.invalid"));
            return Message.error("asl.captcha.invalid");
        }
        Member member = memberService.findListByEmail(email).get(0);
        if (member == null) {
            logger.error(SpringUtils.getMessage("asl.password.memberNotExist"));
            return Message.error("asl.password.memberNotExist");
        }
        if (!member.getEmail().equalsIgnoreCase(email)) {
            logger.error(SpringUtils.getMessage("asl.password.invalidEmail"));
            return Message.error("asl.password.invalidEmail");
        }
        Setting setting = SettingUtils.get();
        SafeKey safeKey = new SafeKey();
        safeKey.setValue(UUID.randomUUID().toString() + DigestUtils.md5Hex(RandomStringUtils.randomAlphabetic(30)));
        safeKey.setExpire(setting.getSafeKeyExpiryTime() != 0 ? DateUtils.addMinutes(new Date(), setting.getSafeKeyExpiryTime()) : null);
        member.setSafeKey(safeKey);
        memberService.update(member);
        mailService.sendFindPasswordMail(member.getEmail(), member.getUsername(), safeKey);

//		System.out.println("## Forget Password Ended...");
        return Message.success("asl.password.mailSuccess");
    }

    /**
     * 重置密码
     */
    @RequestMapping(value = "/reset", method = RequestMethod.GET)
    public String reset(String u, String k, Model model) {
        Member member = memberService.findByUsername(u);
        if (member == null) {
            return ERROR_VIEW;
        }
        SafeKey safeKey = member.getSafeKey();
        if (safeKey == null || safeKey.getValue() == null || !safeKey.getValue().equals(k)) {
            return ERROR_VIEW;
        }
        if (safeKey.hasExpired()) {
            model.addAttribute("erroInfo", Message.warn("asl.password.hasExpired"));
            return ERROR_VIEW;
        }
        model.addAttribute("captchaId", UUID.randomUUID().toString());
        model.addAttribute("member", member);
        model.addAttribute("key", k);
        return "/asl/password/reset";
    }

    /**
     * 重置密码提交
     */
    @RequestMapping(value = "reset", method = RequestMethod.POST)
    public
    @ResponseBody
    Message reset(String captchaId, String captcha, String username, String newPassword, String key) {
        if (!captchaService.isValid(Setting.CaptchaType.resetPassword, captchaId, captcha)) {
            return Message.error("asl.captcha.invalid");
        }
        Member member = memberService.findByUsername(username);
        if (member == null) {
            return ERROR_MESSAGE;
        }
        if (!isValid(Member.class, "password", newPassword, Save.class)) {
            return Message.warn("asl.password.invalidPassword");
        }
        Setting setting = SettingUtils.get();
        if (newPassword.length() < setting.getPasswordMinLength() || newPassword.length() > setting.getPasswordMaxLength()) {
            return Message.warn("asl.password.invalidPassword");
        }
        SafeKey safeKey = member.getSafeKey();
        if (safeKey == null || safeKey.getValue() == null || !safeKey.getValue().equals(key)) {
            return ERROR_MESSAGE;
        }
        if (safeKey.hasExpired()) {
            return Message.error("asl.password.hasExpired");
        }
        member.setPassword(DigestUtils.md5Hex(newPassword));
        safeKey.setExpire(new Date());
        safeKey.setValue(null);
        memberService.update(member);
        return Message.success("asl.password.resetSuccess");
    }

}